package com.ulic.customerManApplication.achievementmodule.action;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ulic.customerManApplication.achievementmodule.bo.Achievement;
import com.ulic.customerManApplication.achievementmodule.bo.SubAchievement;
import com.ulic.customerManApplication.achievementmodule.service.AchievementService;
import com.ulic.customerManApplication.achievementmodule.service.SubAchievementService;
import com.ulic.customerManApplication.achievementmodule.vo.SubAchievementVO;
import com.ulic.customerManApplication.base.BaseAction;
import com.ulic.customerManApplication.commonmodule.service.OrganizationService;
import com.ulic.customerManApplication.commonmodule.vo.ImpDataInfor;
import com.ulic.customerManApplication.constant.CONSTANT;
import com.ulic.customerManApplication.journeylovemodule.bo.JourneyOfLoveActivity;
import com.ulic.customerManApplication.journeylovemodule.service.JourneyLoveService;
import com.ulic.customerManApplication.pager.PagerModel;
import com.ulic.customerManApplication.usermodule.bo.User;
import com.ulic.customerManApplication.util.config.ConfigInfo;
import com.ulic.customerManApplication.util.excel.DownloadDemo;
import com.ulic.customerManApplication.util.excel.DownloadExcel;
import com.ulic.customerManApplication.util.excel.ExpSubAchievements;
import com.ulic.customerManApplication.util.excel.UploadFile;
@Component("subAchievementAction")
@Scope("prototype")
public class SubAchievementAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private SubAchievement subAchievement;
    private File studentsFile;
    private String impDataInfor;
    private String fileName;
    private String journeyLoveId;
    private OrganizationService organizationService = null;
    private SubAchievementService subAchievementService;
    private JourneyLoveService journeyLoveService;
    private AchievementService achievementService;
    private String startcreate;
    private String endcreate;
    private String subCityHidden;
	
	public String getSubCityHidden() {
		return subCityHidden;
	}
	public void setSubCityHidden(String subCityHidden) {
		this.subCityHidden = subCityHidden;
	}
    public String getStartcreate() {
		return startcreate;
	}
	public void setStartcreate(String startcreate) {
		this.startcreate = startcreate;
	}
	public String getEndcreate() {
		return endcreate;
	}
	public void setEndcreate(String endcreate) {
		this.endcreate = endcreate;
	}
	@Resource
	public void setAchievementService(AchievementService achievementService) {
		this.achievementService = achievementService;
	}
     
	@Resource
    public void setJourneyLoveService(JourneyLoveService journeyLoveService) {
		this.journeyLoveService = journeyLoveService;
	}
	@Resource
	public void setSubAchievementService(SubAchievementService subAchievementService) {
		this.subAchievementService = subAchievementService;
	}
	 
	public String getJourneyLoveId() {
		return journeyLoveId;
	}
	public void setJourneyLoveId(String journeyLoveId) {
		this.journeyLoveId = journeyLoveId;
	}
	public SubAchievement getSubAchievement() {
		return subAchievement;
	}
	public void setSubAchievement(SubAchievement subAchievement) {
		this.subAchievement = subAchievement;
	}
	public String getImpDataInfor() {
		return impDataInfor;
	}
	public void setImpDataInfor(String impDataInfor) {
		this.impDataInfor = impDataInfor;
	}
	 
	@Resource
	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}
	public File getStudentsFile() {
		return studentsFile;
	}
	public void setStudentsFile(File studentsFile) {
		this.studentsFile = studentsFile;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		PagerModel pm = subAchievementService.getSubAchievements(curPage);
		httpServletRequest.setAttribute("pm",pm);
		return SUCCESS;
	}
	
	public String searchSubAchievements(){
		
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		String roleName = (String)session.get("rolename");
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		SubAchievementVO subAchievementVO = new SubAchievementVO();
		subAchievementVO.setRoleName(roleName);
		subAchievementVO.setSubAchievement(subAchievement);
		subAchievementVO.setUser(user);
		subAchievementVO.setStartcreate(startcreate);
		subAchievementVO.setEndcreate(endcreate);
		subAchievementVO.setJourneyLoveId(journeyLoveId);
		PagerModel pm = subAchievementService.getSubAchievements(subAchievementVO, curPage);
		JourneyOfLoveActivity joActivity = journeyLoveService.getJourneyLoveById(Integer.parseInt(journeyLoveId));
		if(subAchievement==null){
			subAchievement = new SubAchievement();
		}
		subAchievement.setSubCompany(joActivity.getSubCompany());
		subAchievement.setSubCity(joActivity.getSubCity());
		subAchievement.setSubComName(joActivity.getSubComName());
		subAchievement.setSubCityName(joActivity.getSubCityName());
		httpServletRequest.setAttribute("pm",pm);
		httpServletRequest.setAttribute("journeyLoveId", Integer.parseInt(journeyLoveId));
		httpServletRequest.setAttribute("roleName", roleName);
		return SUCCESS;
	}
	public String toSaveSubAchievement()throws Exception{
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		JourneyOfLoveActivity joActivity = journeyLoveService.getJourneyLoveById(Integer.parseInt(journeyLoveId));
		if(subAchievement==null){
			subAchievement = new SubAchievement();
		}
		subAchievement.setSubCompany(joActivity.getSubCompany());
		subAchievement.setSubCity(joActivity.getSubCity());
		subAchievement.setSubComName(joActivity.getSubComName());
		subAchievement.setSubCityName(joActivity.getSubCityName());
		httpServletRequest.setAttribute("journeyLoveId", httpServletRequest.getParameter("journeyLoveId"));
		return SUCCESS;
	}
	public String saveSubAchievement()throws Exception{
		subAchievement.setSub_createDate(new Date());
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		subAchievement.setSub_user(user);
		subAchievement.setSub_journeyOfLoveActivity(journeyLoveService.getJourneyLoveById(Integer.parseInt(journeyLoveId)));
		subAchievementService.insertSubAchievement(subAchievement);
		addAchievement(subAchievement);
		return SUCCESS;
	}
	public String viewSubAchievement()throws Exception{
		subAchievement = subAchievementService.getSubAchievement(subAchievement.getSub_id());
		return SUCCESS;
	}
	public String updateSubAchievement()throws Exception{
		subAchievement = subAchievementService.getSubAchievement(subAchievement.getSub_id());
		return SUCCESS;
	}
	public String updatedSubAchievement()throws Exception{
		 User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		 subAchievement.setSub_user(user);
		 JourneyOfLoveActivity journeyLove = journeyLoveService.getJourneyLoveById(Integer.parseInt(journeyLoveId));
         subAchievement.setSub_journeyOfLoveActivity(journeyLove);
		 subAchievementService.updateSubAchievement(subAchievement);
		 return SUCCESS;
	}
	public String deleteSubAchievement()throws Exception{
		subAchievement = subAchievementService.getSubAchievement(subAchievement.getSub_id());
		subAchievementService.deleteSubAchievement(subAchievement);
		return SUCCESS;
	}
	
	public String toImpSubAchievements(){
		return SUCCESS;
	}
	public String impSubAchievements() throws Exception{
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		long date = new Date().getTime();
		ImpDataInfor impDataInfor = new ImpDataInfor();
		List<Integer> errorNumbers = new ArrayList<Integer>();
		String realPath = ConfigInfo.getPropertiesValue("uploadfile.path");
		if(fileName != null && fileName.length() !=0){
			fileName = UploadFile.upload(studentsFile, fileName,date);//先将文件上传到服务器
			File f = new File(realPath+"/"+fileName);  
			List<SubAchievement> subAchievements = new ArrayList<SubAchievement>();
			SubAchievement subach = null;
			try {   
				FileInputStream is = new FileInputStream(f);  //读取服务器上的文件 
				HSSFWorkbook wbs = new HSSFWorkbook(is);   
				HSSFSheet childSheet = wbs.getSheetAt(0); 
				 for (int j = 1; j <=  childSheet.getLastRowNum(); j++) {   
						HSSFRow row = childSheet.getRow(j);   
						subach = new SubAchievement();
						if (null != row) {   
							for (int k = 0; k <3; k++) {   
								String value = null;
								HSSFCell cell = row.getCell((short)k);   
								if (null != cell) {   
									switch (cell.getCellType()) {   
									case HSSFCell.CELL_TYPE_NUMERIC: // 数字   
										System.out.print(cell.getNumericCellValue()   
												+ "   ");
										break;   
									case HSSFCell.CELL_TYPE_STRING: // 字符串   
										System.out.print(cell.getStringCellValue()   
												+ "   "); 
										value = cell.getStringCellValue();
										break;   
									case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean   
										System.out.println(cell.getBooleanCellValue()   
												+ "   ");   
										break;   
									case HSSFCell.CELL_TYPE_FORMULA: // 公式   
										System.out.print(cell.getCellFormula() + "   ");   
										break;   
									case HSSFCell.CELL_TYPE_BLANK: // 空值   
										System.out.println(" ");   
										break;   
									case HSSFCell.CELL_TYPE_ERROR: // 故障   
										System.out.println(" ");   
										break;   
									default:   
										System.out.print("未知类型   ");   
										break;   
									} 
									
								} else {   
									System.out.print("-   ");   
									value="";
								} 
								switch(k){
								case 0:
									subach.setSub_achieveName(value);
									break;
								case 1:
									subach.setSub_achieveNumber(value);
									break;
								case 2:
									subach.setSub_school(value);
									break;
								default:  
									break;
								}
							}   
						}
						JourneyOfLoveActivity jActivity = journeyLoveService.getJourneyLoveById(Integer.parseInt(journeyLoveId));
                        subach.setSub_journeyOfLoveActivity(jActivity);
						subach.setSub_createDate(new Date()); 
						subach.setSub_user(user);
						subach.setSubCompany(jActivity.getSubCompany());
						subach.setSubCity(jActivity.getSubCity());
						subach.setSubComName(jActivity.getSubComName());
						subach.setSubCityName(jActivity.getSubCityName());
						
						subAchievements.add(subach);
						addAchievement(subach);
					}
				    subAchievementService.insertSubAchievements(subAchievements);//将从文件读取到的数据封装到对象 持久化到数据库
					impDataInfor.setTotalNum(childSheet.getLastRowNum());
					impDataInfor.setSucceedNum(childSheet.getLastRowNum() - errorNumbers.size());
					impDataInfor.setFailNum(errorNumbers.size());
					String errorDetail = "";
					if(errorNumbers.size()!=0){
						for(Integer num : errorNumbers){
							errorDetail = errorDetail+num+" ";
						}
					}
					impDataInfor.setFailDetail(errorDetail);
					impDataInfor.setFailResaon("1");
			} catch (Exception e) {   
				e.printStackTrace();   
			} 
		}
		this.setImpDataInfor(impDataInfor.toString());
		return SUCCESS;
	}
	
	public String expSubAchievements(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		HttpServletResponse httpServletResponse = ServletActionContext.getResponse();
		String realPath = httpServletRequest.getRealPath("/download/");
		String fileName = "成果信息.xls";
		String[] headers = {"分公司","中支","名称","中支","学校"}; 
		List<SubAchievement> subAchievements = subAchievementService.getSubAchievementsByJourId(Integer.parseInt(journeyLoveId));
		ExpSubAchievements.exp(headers,subAchievements,realPath+"/"+fileName);//将数据读取到服务器上的文件中
	    DownloadExcel.download(realPath,fileName,httpServletRequest,httpServletResponse);//从服务器上下载文件
		return null;
	}
	
	public String expDemo(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		HttpServletResponse httpServletResponse = ServletActionContext.getResponse();
		String realPath = httpServletRequest.getRealPath("/download/");
		DownloadDemo.download(realPath,"AchievementDemo.xls;成果信息模板.xls",httpServletRequest,httpServletResponse);//从服务器上下载文件
		return null;
	}
	
	public void addAchievement(SubAchievement subAchievement)throws Exception{
		Achievement achievement = new Achievement();
		achievement.setAchieveName(subAchievement.getSub_achieveName());
		achievement.setCreateDate(subAchievement.getSub_createDate());
		achievement.setAchieveNumber(subAchievement.getSub_achieveNumber());
		achievement.setSchool(subAchievement.getSub_school());
		achievement.setSubCity(subAchievement.getSubCity());
		achievement.setSubCompany(subAchievement.getSubCompany());
		achievement.setUser(subAchievement.getSub_user());
		achievement.setSubComName(subAchievement.getSubComName());
		achievement.setSubCityName(subAchievement.getSubCityName());
		achievementService.insertAchievement(achievement);
	}
}
